﻿using BarTender;
using IntoCommon.Util;
using IntoStationSystem.Db;
using IntoStationSystem.Global;
using IntoStationSystem.PLC;
using IntoStationSystem.ViewModels;
using System;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using static IntoStationSystem.Global.Events;

namespace IntoStationSystem.ExDevice
{
    /// <summary>
    /// 串口设备
    /// </summary>
    public class SerialPortDev
    {
        public string ScanCode = string.Empty;
        /// <summary>
        /// 依次排列为：电压、电流、频率、占空比、风机结果
        /// </summary>
        public float[] ElectriDatas = new float[5];
        /// <summary>
        /// 压力值、泄露值
        /// </summary>
        private float[] GasDatas = new float[2];

        public bool IsOpen = false;
        //是否允许扫码
        public bool IsEnable = false;
        public int step = 0;
        public int ProgramNumber = 0;

        public string SerialType = string.Empty;

        private SerialPort serialPort = new SerialPort();

        public float CollectionSteps = 0;


        public SerialPortDev(string portName, int baudRate, string type)
        {
            this.SerialType = type;
            Open(portName, baudRate);
           
            switch (type)
            {
                case "Fan1":
                    EventRepository.EventAggregator.GetEvent<StartFan1Event>().Subscribe(StartFan);
                    EventRepository.EventAggregator.GetEvent<StopFan1Event>().Subscribe(StopFan);
                    break;
                case "Fan2":
                    EventRepository.EventAggregator.GetEvent<StartFan2Event>().Subscribe(StartFan);
                    EventRepository.EventAggregator.GetEvent<StopFan2Event>().Subscribe(StopFan);
                    break;
            }
        }

        private void StartFan()
        {

            Task.Run(() =>
            {

                while (true)
                {
                    if (ProgramNumber != 0)
                    {
                        //发送命令启动
                        string start = "EB 90 50 00 00";
                        byte[] data = GlobalFunc.HexStringToBytes(start);
                        data[3] = (byte)(Convert.ToInt32(ProgramNumber.ToString(), 16));
                        //Console.WriteLine("data[3]:" + data[3]);
                        data[4] = (byte)(data[2] + data[3]);
                        //Console.WriteLine("data[4]:" + data[4]);
                        if (IsOpen)
                        {
                            //DbHelper.Log("风机写入启动");
                            //Log("风机写入启动");
                            serialPort.Write(data, 0, data.Length);
                            switch (SerialType)
                            {
                                case "Fan1":
                                    //DbHelper.Log("风机1启动");
                                    //Log("风机1启动");
                                    break;
                                case "Fan2":
                                    //DbHelper.Log("风机2启动");
                                    //Log("风机2启动");
                                    break;
                            }
                        }
                        break;
                    }
                }
            });
        }

        private void StopFan()
        {
            string stop = "EB 90 53 00 00";
            byte[] data = GlobalFunc.HexStringToBytes(stop);
            data[3] = (byte)(Convert.ToInt32(ProgramNumber.ToString(), 16));
            data[4] = (byte)(data[2] + data[3]);
            if (IsOpen)
            {
                serialPort.Write(data, 0, data.Length);
                switch (SerialType)
                {
                    case "Fan1":
                        //DbHelper.Log("风机1停止");
                        break;
                    case "Fan2":
                        //DbHelper.Log("风机2停止");
                        break;
                }
            }
        }

        public void Open(string portName,int baudRate )
        {
            try
            {
                serialPort = new SerialPort();
                serialPort.PortName = portName;
                serialPort.BaudRate = baudRate;
                serialPort.DataReceived += Received;
                serialPort.Open();
                IsOpen = serialPort.IsOpen;
            }
            catch (Exception e)
            {
                DbHelper.Log($"{SerialType} :{e.Message.ToString()}");
            }
        }

        private void Received(object sender, SerialDataReceivedEventArgs e)

        {
            try
            {
                Thread.Sleep(200);
                int len = serialPort.BytesToRead;
                byte[] datas = new byte[len];

                serialPort.Read(datas, 0, len);
                string temp = Encoding.ASCII.GetString(datas);
                switch (SerialType)
                {
                    case "Scan":

                        if (IsEnable)
                        {
                            ScanCode = temp.Trim();
                        }
                        break;
                    case "Fan1":
                    case "Fan2":
                        //DbHelper.Log("len:" + len);
                        //Log("len:" + len);
                        if (len>14)
                        {
                            if (SerialType == "Fan1")
                            {
                                int a = 1;

                            }
                            else if(SerialType == "Fan2")
                            {
                                int b = 1;
                            }

                            ElectriDatas[0] = (datas[4] * 256 + datas[5]) / 100f;   //电压                       
                            ElectriDatas[1] = (datas[6] * 256 + datas[7]) / 100f;   //电流                        
                            ElectriDatas[2] = datas[8] * 256 + datas[9];            //频率                        
                            ElectriDatas[3] = datas[10];                            //占空比                        
                            double level = datas[11];                               //电平                        
                            double gear = datas[12];                                //运行挡位
                            ElectriDatas[4] = datas[13] == 0 ? 1 : 2;                            //状态 0 OK 1 NG
                                                                                                 //Console.WriteLine("步骤:" + step);
                                                                                                 //Console.WriteLine("运行完成步骤:" + ((int)datas[3]+1));
                                                                                                 //Console.WriteLine("结果:" + ElectriDatas[4]);
                            //Log(SerialType + "抓取的步骤:" + CollectionSteps+"---结果："+(int)ElectriDatas[4]);                                                                    //DbHelper.Log(SerialType + "运行完成步骤:" + ((int)datas[3] + 1));
                            //Log(SerialType + "运行完成步骤:" + ((int)datas[3] + 1));
                            if ((int)datas[3] + 1 == CollectionSteps || (int)ElectriDatas[4] == 2)
                            {
                                if (SerialType == "Fan1")
                                {
                                    //DbHelper.Log("风机1检测完成开始");
                                    //Log("风机1检测完成开始");
                                    Locator.Instance.Service.WriteData(Fields.Map["Group1SetReal"].First, ElectriDatas);
                                    
                                    //DbHelper.Log("风机1检测完成结束");
                                    //Log("风机1检测完成结束");
                                }
                                else
                                {
                                    // DbHelper.Log("风机2检测完成开始");
                                    //Log("风机2检测完成开始");
                                    Locator.Instance.Service.WriteData(Fields.Map["Group2SetReal"].First, ElectriDatas);
                                    //DbHelper.Log("风机2检测完成结束");
                                    //Log("风机2检测完成结束");
                                }
                                serialPort.Close();
                                serialPort.Dispose(); // 显式调用Dispose方法释放资源
                                IsOpen = false;
                                serialPort = null;
                            }
                        }

                        break;
                    case "Gas":

                       
                        var bb = temp.Split(':');
                        GasDatas[0] = (float)Convert.ToDouble(bb[1].Split(' ')[0]);                    //压力
                        
                        int result = Regex.Replace(temp, @"(.*\()(.*)(\).*)", "$2") == "OK" ? 0 : 1;    //结果  0 OK 1 NG
                        if (Regex.IsMatch(bb[3].Split(' ')[0], @"^^[-+]?[0-9]*\.?[0-9]+$"))
                        {
                            GasDatas[1] = (float)Convert.ToDouble(bb[3].Split(' ')[0]);                //泄露
                        }
                        else
                        {
                            GasDatas[1] = -100;                                                        //泄露
                        }
                      
                  
                        Locator.Instance.Service.WriteData(Fields.Map["Group1SetReal"].First + 20, GasDatas);
                      
                        break;
                }

            }
            catch (Exception ex)
            {
                //DbHelper.Log($"串口{SerialType}接收数据错误");
                Log($"串口{SerialType}接收数据错误-------"+ex.Message);
            }
        }


        private static void Log(string message)
        {
            //using (StreamWriter writer = new StreamWriter("D:/messge.txt", append: true))
            //{
            //    string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
            //    writer.WriteLine(logMessage);
            //}
        }
    }
}
